package com.villaday.idf.wxapi;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.ShowMessageFromWX;
import com.tencent.mm.opensdk.modelmsg.WXAppExtendObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.AppContext;
import com.villaday.idf.MainActivity;
import com.villaday.idf.R;
import com.villaday.idf.activity.BindPhone_V3Activity;
import com.villaday.idf.activity.LoginActivity;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.BaseWXActivity;
import com.villaday.idf.model.Code;
import com.villaday.idf.model.LoginEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;

import java.util.HashMap;
import java.util.Map;


public class WXEntryActivity extends BaseWXActivity implements IWXAPIEventHandler, OkHttpUtil.OnDataListener {

    private IWXAPI api;
    private String getTokenUrl;
    private String getUserInfoUrl;
    private String openId;
    private String token;
    private Gson gson = new GsonBuilder().create();


    @Override
    protected int getViewResId() {
        return R.layout.activity_wechat;
    }

    @Override
    protected void init() {

        api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {
        Log.e("loge", "values: onResp");


        switch (baseReq.getType()) {
            case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                goToGetMsg();
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                goToShowMsg();
                break;
            default:
                break;
        }




    }

    @Override
    public void onResp(BaseResp baseResp) {
        switch (baseResp.getType()) {
            case 1://登录
                switch (baseResp.errCode) {
                    case BaseResp.ErrCode.ERR_OK:
                        String code = ((SendAuth.Resp) baseResp).code;
//                        String code = "0212HDPr0ZSice1XEWPr0QMHPr02HDPN";
                        String lang = ((SendAuth.Resp) baseResp).lang;
                        Map<String, Object> map = new HashMap<>();
                        OkHttpUtil.postJson(this, Constant.URL.login, new Code(2, lang, code), map, this);
                        break;
                    default:
                        Toast.makeText(this, "授权未成功", Toast.LENGTH_SHORT).show();
                        finish();
                        break;
                }
                break;
            case 2://分享
                switch (baseResp.errCode) {
                    case BaseResp.ErrCode.ERR_OK://成功
                        // Toast.makeText(this, "分享成功", Toast.LENGTH_SHORT).show();
                        break;
                    case BaseResp.ErrCode.ERR_USER_CANCEL://用户取消
                        // Toast.makeText(this, "用户取消", Toast.LENGTH_SHORT).show();
                        break;
                    case BaseResp.ErrCode.ERR_SENT_FAILED://发送失败
                        // Toast.makeText(this, "发送失败", Toast.LENGTH_SHORT).show();
                        break;
                    case BaseResp.ErrCode.ERR_AUTH_DENIED://授权失败
                        // Toast.makeText(this, "授权失败", Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        //Toast.makeText(this, "分享失败", Toast.LENGTH_SHORT).show();
                        break;
                }
                finish();
                break;
            case ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM: {//小程序
                WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp) baseResp;
                String extraData =launchMiniProResp.extMsg; //对应小程序组件 <button open-type="launchApp"> 中的 app-parameter 属性
                //初始化推送
                AppContext.getInstance().initPush();
                Intent intent = new Intent(this, MainActivity.class);


                intent.putExtra("page",2);
                startActivity(intent);
                finish();
                break;


            } case ConstantsAPI.COMMAND_GETMESSAGE_FROM_WX:
                goToGetMsg();
                break;
            case ConstantsAPI.COMMAND_SHOWMESSAGE_FROM_WX:
                goToShowMsg();
                break;
            default:
                break;


        }
    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.login.equals(url)) {
                LogeUtil.e("login", json);
                LoginEntity loginEntity = gson.fromJson(json, LoginEntity.class);
                if (loginEntity.getCode().equals("200")) {
                    SharedPreferencesUtil.saveToken(this, loginEntity.getBody().getToken());
                    SharedPreferencesUtil.saveUserInfo(this, json);
                    SharedPreferencesUtil.saveRoleInfo(this, json);
                    if (TextUtils.isEmpty(loginEntity.getBody().getMember().getMobile())){//没绑定
                        Intent intent = new Intent(this, BindPhone_V3Activity.class);
                        startActivity(intent);
                    }else {
                        //初始化推送
                        AppContext.getInstance().initPush();

                        Intent intent = new Intent(this, MainActivity.class);
                        startActivity(intent);
                    }




                } else {
                    ToastUtil.initToast(this, loginEntity.getMsg());
                    Intent intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);

                }
                finish();

            }
            /*if (getTokenUrl.equals(url)) {//获取access_token
                WeChatTokenEntity weChatToken = new Gson().fromJson(json, WeChatTokenEntity.class);
                token = weChatToken.getAccess_token();
                openId = weChatToken.getOpenid();
                String jsonString = gson.toJson(new Login("微信快捷", openId, "default"));
                OkHttpUtil.postJson(Constant.URL.Login, DesUtil.encrypt(jsonString), this);
            } else if (Constant.URL.Login.equals(url)) {//登录
                String decrypt = DesUtil.decrypt(json);
                RegisterEntity loginEntity = new Gson().fromJson(decrypt, RegisterEntity.class);
                if ("0".equals(loginEntity.getErrNum())) {//登录成功
                    ToastUtil.showToast(this, loginEntity.getErrMsg());
                    afterLogin(loginEntity.getData().get(0).getUserId());
                } else if ("-2".equals(loginEntity.getErrNum())){//无此快捷账户
                    getUserInfoUrl = String.format(Constant.URL.WeChatInfo, token, openId);
                    LoadingDialog loadingDialog = LoadingDialog.newInstance("获取基本信息中");
                    loadingDialog.show(getFragmentManager(), "loading");
                    OkHttpUtil.getJSON(getUserInfoUrl, this);
                } else {//登录失败
                    ToastUtil.showToast(this, loginEntity.getErrMsg());
                    finish();
                }
            } else if (getUserInfoUrl.equals(url)) {//获取微信基本信息
                SharedPreferences WeChatInfo = getSharedPreferences("WeChatInfo", MODE_PRIVATE);
                SharedPreferences.Editor editor = WeChatInfo.edit();
                editor.putString("info", json);
                editor.commit();
                Intent intentBind = new Intent(WXEntryActivity.this, BindMobileActivity.class);
                intentBind.putExtra("loginType", "微信快捷");
                intentBind.putExtra("openId", openId);
                startActivity(intentBind);
                finish();
            }*/
        }
    }

    private void afterLogin(String userId) {
       /* //用户信息加密后保存到本地
        SharedPreferences userShared = getSharedPreferences("user", MODE_PRIVATE);
        SharedPreferences.Editor editor = userShared.edit();
        editor.putString("UserId", DesUtil.encrypt(userId, DesUtil.LOCAL_KEY));
        editor.putLong("LoginTime", System.currentTimeMillis());
        editor.commit();
        setResult(RESULT_OK);
        finish();*/
    }

    @Override
    public void onFailure(String url, String error) {
    }


    private void goToGetMsg() {
       /* Intent intent = new Intent(this, GetFromWXActivity.class);
        intent.putExtras(getIntent());
        startActivity(intent);
        finish();*/

        //初始化推送
        AppContext.getInstance().initPush();
        Intent intent = new Intent(this, MainActivity.class);


        intent.putExtra("page",2);
        startActivity(intent);
        finish();


    }

    private void goToShowMsg() {
        /*WXMediaMessage wxMsg = showReq.message;
        WXAppExtendObject obj = (WXAppExtendObject) wxMsg.mediaObject;

        StringBuffer msg = new StringBuffer(); // 组织一个待显示的消息内容
        msg.append("description: ");
        msg.append(wxMsg.description);
        msg.append("\n");
        msg.append("extInfo: ");
        msg.append(obj.extInfo);
        msg.append("\n");
        msg.append("filePath: ");
        msg.append(obj.filePath);

        Intent intent = new Intent(this, ShowFromWXActivity.class);
        intent.putExtra(Constants.ShowMsgActivity.STitle, wxMsg.title);
        intent.putExtra(Constants.ShowMsgActivity.SMessage, msg.toString());
        intent.putExtra(Constants.ShowMsgActivity.BAThumbData, wxMsg.thumbData);
        startActivity(intent);
        finish();*/

        //初始化推送
        AppContext.getInstance().initPush();
        Intent intent = new Intent(this, MainActivity.class);


        intent.putExtra("page",2);
        startActivity(intent);
        finish();
    }
}